using UnityEngine;

public class MovingPlatform : MonoBehaviour
{
    public Transform pointA;
    public Transform pointB;
    public float speed = 2f;
    private Vector3 start;
    private Vector3 end;
    private float t;
    private Transform playerOnPlatform;

    void Start()
    {
        start = pointA.position;
        end = pointB.position;
    }

    void Update()
    {
        t += Time.deltaTime * speed;
        transform.position = Vector3.Lerp(start, end, Mathf.PingPong(t, 1f));
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            playerOnPlatform = collision.transform;
            collision.transform.SetParent(transform);
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            if (collision.transform.parent == transform)
            {
                collision.transform.SetParent(null);
            }
            playerOnPlatform = null;
        }
    }

    private void OnDisable()
    {
        if (playerOnPlatform != null && playerOnPlatform.parent == transform)
        {
            playerOnPlatform.SetParent(null);
            playerOnPlatform = null;
        }
    }
}